import { create } from 'zustand';
import { devtools, subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type {
  SearchResult,
  SearchSuggestion,
  SearchFilters,
  SearchHistory,
  LoadingState,
} from '@/types';
import { searchAPI } from '@/services/api';

// 搜索状态接口
interface SearchState {
  // 搜索状态
  query: string;
  results: SearchResult[];
  suggestions: SearchSuggestion[];
  history: SearchHistory[];
  filters: SearchFilters;
  
  // 加载状态
  searchLoading: LoadingState;
  suggestionsLoading: LoadingState;
  
  // 分页信息
  pagination: {
    page: number;
    pageSize: number;
    total: number;
    hasMore: boolean;
  };
  
  // 错误信息
  error: string | null;
  
  // 搜索统计
  stats: {
    totalResults: number;
    searchTime: number;
    lastSearchAt: number | null;
  };
  
  // UI 状态
  showSuggestions: boolean;
  selectedSuggestionIndex: number;
}

// 搜索动作接口
interface SearchActions {
  // 基础动作
  setQuery: (query: string) => void;
  setResults: (results: SearchResult[]) => void;
  setSuggestions: (suggestions: SearchSuggestion[]) => void;
  setFilters: (filters: Partial<SearchFilters>) => void;
  setError: (error: string | null) => void;
  
  // 复合动作
  performSearch: (query?: string, options?: { append?: boolean }) => Promise<void>;
  loadMoreResults: () => Promise<void>;
  getSuggestions: (query: string) => Promise<void>;
  clearSearch: () => void;
  clearSuggestions: () => void;
  
  // 历史记录
  addToHistory: (query: string, resultCount: number) => void;
  clearHistory: () => void;
  removeFromHistory: (id: string) => void;
  
  // UI 控制
  showSuggestionsPanel: () => void;
  hideSuggestionsPanel: () => void;
  selectSuggestion: (index: number) => void;
  selectNextSuggestion: () => void;
  selectPrevSuggestion: () => void;
  
  // 工具方法
  reset: () => void;
}

// 初始状态
const initialState: SearchState = {
  query: '',
  results: [],
  suggestions: [],
  history: [],
  filters: {},
  searchLoading: 'idle',
  suggestionsLoading: 'idle',
  pagination: {
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: false,
  },
  error: null,
  stats: {
    totalResults: 0,
    searchTime: 0,
    lastSearchAt: null,
  },
  showSuggestions: false,
  selectedSuggestionIndex: -1,
};

// 创建搜索状态管理 store
export const useSearchStore = create<SearchState & SearchActions>()(
  devtools(
    subscribeWithSelector(
      immer((set, get) => ({
        ...initialState,

        // 基础动作
        setQuery: (query: string) => {
          set((state) => {
            state.query = query;
            if (!query.trim()) {
              state.suggestions = [];
              state.showSuggestions = false;
            }
          });
        },

        setResults: (results: SearchResult[]) => {
          set((state) => {
            state.results = results;
            state.searchLoading = 'success';
          });
        },

        setSuggestions: (suggestions: SearchSuggestion[]) => {
          set((state) => {
            state.suggestions = suggestions;
            state.suggestionsLoading = 'success';
            state.selectedSuggestionIndex = -1;
          });
        },

        setFilters: (filters: Partial<SearchFilters>) => {
          set((state) => {
            state.filters = { ...state.filters, ...filters };
          });
        },

        setError: (error: string | null) => {
          set((state) => {
            state.error = error;
            if (error) {
              state.searchLoading = 'error';
            }
          });
        },

        // 执行搜索
        performSearch: async (query?: string, options = {}) => {
          const { append = false } = options;
          const searchQuery = query || get().query;
          
          if (!searchQuery.trim()) {
            return;
          }

          set((state) => {
            state.searchLoading = 'loading';
            state.error = null;
            if (!append) {
              state.results = [];
              state.pagination.page = 1;
            }
          });

          try {
            const startTime = Date.now();
            const currentState = get();
            
            const response = await searchAPI.search({
              text: searchQuery,
              filters: currentState.filters,
              pagination: {
                page: append ? currentState.pagination.page + 1 : 1,
                pageSize: currentState.pagination.pageSize,
              },
            });

            const searchTime = Date.now() - startTime;

            set((state) => {
              if (append) {
                state.results.push(...response.results);
                state.pagination.page += 1;
              } else {
                state.results = response.results;
                state.pagination.page = 1;
              }
              
              state.pagination.total = response.pagination.total;
              state.pagination.hasMore = response.pagination.hasNext;
              state.searchLoading = 'success';
              state.stats.totalResults = response.pagination.total;
              state.stats.searchTime = searchTime;
              state.stats.lastSearchAt = Date.now();
              state.showSuggestions = false;
            });

            // 添加到搜索历史
            get().addToHistory(searchQuery, response.pagination.total);

          } catch (error: any) {
            set((state) => {
              state.searchLoading = 'error';
              state.error = error.message || '搜索失败，请稍后重试';
            });
          }
        },

        // 加载更多结果
        loadMoreResults: async () => {
          const state = get();
          if (!state.pagination.hasMore || state.searchLoading === 'loading') {
            return;
          }

          await get().performSearch(undefined, { append: true });
        },

        // 获取搜索建议
        getSuggestions: async (query: string) => {
          if (!query.trim()) {
            set((state) => {
              state.suggestions = [];
              state.showSuggestions = false;
            });
            return;
          }

          set((state) => {
            state.suggestionsLoading = 'loading';
          });

          try {
            const suggestions = await searchAPI.getSuggestions(query);
            
            set((state) => {
              state.suggestions = suggestions;
              state.suggestionsLoading = 'success';
              state.showSuggestions = suggestions.length > 0;
            });
          } catch (error) {
            set((state) => {
              state.suggestionsLoading = 'error';
              state.suggestions = [];
              state.showSuggestions = false;
            });
          }
        },

        // 清除搜索
        clearSearch: () => {
          set((state) => {
            state.query = '';
            state.results = [];
            state.error = null;
            state.searchLoading = 'idle';
            state.pagination = initialState.pagination;
            state.stats = initialState.stats;
          });
        },

        // 清除建议
        clearSuggestions: () => {
          set((state) => {
            state.suggestions = [];
            state.showSuggestions = false;
            state.selectedSuggestionIndex = -1;
            state.suggestionsLoading = 'idle';
          });
        },

        // 添加到历史记录
        addToHistory: (query: string, resultCount: number) => {
          set((state) => {
            const existingIndex = state.history.findIndex((item: any) => item.query === query);
            const historyItem = {
              id: `history_${Date.now()}`,
              query,
              timestamp: Date.now(),
              resultCount,
            };

            if (existingIndex >= 0) {
              // 更新现有记录
              state.history[existingIndex] = historyItem;
            } else {
              // 添加新记录，保持最多50条
              state.history.unshift(historyItem);
              if (state.history.length > 50) {
                state.history = state.history.slice(0, 50);
              }
            }
          });
        },

        // 清除历史记录
        clearHistory: () => {
          set((state) => {
            state.history = [];
          });
        },

        // 删除历史记录项
        removeFromHistory: (id: string) => {
          set((state) => {
            state.history = state.history.filter((item: any) => item.id !== id);
          });
        },

        // UI 控制
        showSuggestionsPanel: () => {
          set((state) => {
            state.showSuggestions = true;
          });
        },

        hideSuggestionsPanel: () => {
          set((state) => {
            state.showSuggestions = false;
            state.selectedSuggestionIndex = -1;
          });
        },

        selectSuggestion: (index: number) => {
          set((state) => {
            state.selectedSuggestionIndex = index;
          });
        },

        selectNextSuggestion: () => {
          set((state) => {
            const maxIndex = state.suggestions.length - 1;
            state.selectedSuggestionIndex = Math.min(state.selectedSuggestionIndex + 1, maxIndex);
          });
        },

        selectPrevSuggestion: () => {
          set((state) => {
            state.selectedSuggestionIndex = Math.max(state.selectedSuggestionIndex - 1, -1);
          });
        },

        // 重置状态
        reset: () => {
          set(initialState);
        },
      }))
    ),
    {
      name: 'search-store',
      partialize: (state: any) => ({
        history: state.history,
        filters: state.filters,
      }),
    }
  )
);

// 选择器 hooks
export const useSearchQuery = () => useSearchStore(state => state.query);
export const useSearchResults = () => useSearchStore(state => state.results);
export const useSearchSuggestions = () => useSearchStore(state => state.suggestions);
export const useSearchLoading = () => useSearchStore(state => state.searchLoading);
export const useSearchError = () => useSearchStore(state => state.error);
export const useSearchHistory = () => useSearchStore(state => state.history);
export const useSearchFilters = () => useSearchStore(state => state.filters);
export const useSearchPagination = () => useSearchStore(state => state.pagination);
export const useSearchStats = () => useSearchStore(state => state.stats);

// 动作 hooks
export const useSearchActions = () => useSearchStore(state => ({
  setQuery: state.setQuery,
  performSearch: state.performSearch,
  loadMoreResults: state.loadMoreResults,
  getSuggestions: state.getSuggestions,
  clearSearch: state.clearSearch,
  setFilters: state.setFilters,
  addToHistory: state.addToHistory,
  clearHistory: state.clearHistory,
  showSuggestionsPanel: state.showSuggestionsPanel,
  hideSuggestionsPanel: state.hideSuggestionsPanel,
  selectSuggestion: state.selectSuggestion,
  selectNextSuggestion: state.selectNextSuggestion,
  selectPrevSuggestion: state.selectPrevSuggestion,
}));
